/**
 * 
 */
package com.ydy.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.ydy.annotation.AdminToken;
import com.ydy.constant.SystemConstant;
import com.ydy.ienum.EnumSystem;
import com.ydy.interceptor.base.BaseInterceptor;
import com.ydy.model.Admin;
import com.ydy.utils.TokenUtil;
import com.ydy.vo.other.BaseVo;
import com.ydy.vo.other.ResultVo;

/**
 * 权限token拦截器
 * 
 * @author xuzhaojie
 *
 *         2019年1月16日 下午20:04:07
 */
@Component
public class AdminTokenInterceptor extends BaseInterceptor {

	// private final static Logger log =
	// LoggerFactory.getLogger(AdminTokenInterceptor.class);

	// 在控制器执行前调用
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod m = (HandlerMethod) handler;// 强转原来的类型
			AdminToken an = m.getMethod().getAnnotation(AdminToken.class);// 查看该方法有无权限注解
			if (an == null) {// 没有该注解，放行
				return true;
			}
			String token = request.getParameter("token");
			if (token == null || "".equals(token)) {
				BaseVo vo = new ResultVo(EnumSystem.ADMIN_TOKEN_NOT_EXSIT);
				handleResponse(response, vo);
				return false;
			}
			try {
				Admin admin = TokenUtil.getAdmin(token);// 解释cookie,获取admin信息
				request.setAttribute(SystemConstant.ADM_TOKEN, admin);
				// 后续涉及权限等级再完善
				admin.toString();
				return true;
			} catch (TokenExpiredException e) {
				BaseVo vo = new ResultVo(EnumSystem.TOKEN_EXPIRED);
				handleResponse(response, vo);
				return false;
			} catch (JWTDecodeException e) {
				BaseVo vo = new ResultVo(EnumSystem.TOKEN_HAD_MODIFY);
				handleResponse(response, vo);
				return false;
			} catch (Exception e) {
				BaseVo vo = new ResultVo(EnumSystem.TOKEN_NOT_MATCH);
				handleResponse(response, vo);
				return false;
			}
		} else {
			return true;
		}
	}

}
